import { Feature } from "ol";
import GeoJSON from "ol/format/GeoJSON";
import Geometry from "ol/geom/Geometry";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import Style from "ol/style/Style";
import { Text } from "ol/style";

const geoJSONMaker = new GeoJSON();

export function newFeatureFromGeoJSON(geoJSON: any): Feature<any> {
  return geoJSONMaker.readFeature(geoJSON);
}

export function newLayerFromGeoJSON(
  geoJSON: Array<any>,
  options: {
    style?: Style;
    addText?: boolean;
  } = { style: undefined, addText: false }
): VectorLayer<VectorSource<Geometry>> {
  const features: Array<Feature<any>> = geoJSON.map((x) => {
    const feature: Feature<any> = newFeatureFromGeoJSON(x);
    if (options.style !== undefined) {
      feature.setStyle((feature, resolution) => {
        if (options.style !== undefined) {
          const style = options.style.clone();
          if (options.addText && resolution < 0.000015) {
            style.setText(
              new Text({
                text: feature.get("名称"),
                offsetY: 6,
                textBaseline: "top",
                font: "11px bold",
              })
            );
          }
          return style;
        }
      });
    }
    return feature;
  });
  return new VectorLayer({
    source: new VectorSource({
      features: features,
    }),
  });
}
